package com.kalvan.admin.gateway.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.kalvan.client.context.RequestContextHolder;
import com.kalvan.client.exception.BizException;
import com.kalvan.commons.constant.AdminContextCacheKey;
import com.kalvan.commons.constant.AdminReturnCode;
import com.kalvan.commons.constant.AuditState;
import com.kalvan.commons.constant.State;
import com.kalvan.commons.db.DataSourceConstants;
import com.kalvan.commons.db.gateway.mapper.GatewayRouteMapper;
import com.kalvan.commons.db.gateway.model.GatewayRoute;
import com.kalvan.db.mybatis.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 网关路由表Service实现类
 *
 * @author kalvan
 */
@Slf4j
@Service("gatewayRouteService")
public class GatewayRouteService extends BaseService<GatewayRoute> {
    @Resource
    GatewayRouteMapper mapper;

    @Override
    public void processParams(Map<String, Object> params) {
        // TODO 查询和下载的条件检查
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int add(GatewayRoute gatewayRoute) {
        // TODO 填充数据,选择字段进行检查，更新人，更新时间，查重
        GatewayRoute gatewayRouteQuery = new GatewayRoute();

        if (mapper.selectCount(gatewayRouteQuery) > 0) {
            throw new BizException(AdminReturnCode.DATA_REPEAT);
        }
        gatewayRoute.setAuditApplicant(String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME)));
        // TODO 新增审核,业务状态不生效,审核状态为待审核
        gatewayRoute.setState(State.DISABLE.getCode());
        gatewayRoute.setAuditState(AuditState.ADD.getCode());
        return mapper.insertSelective(gatewayRoute);
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int edit(GatewayRoute gatewayRoute) {
        GatewayRoute gatewayRouteDb = mapper.selectByUk(gatewayRoute.getId());
        if (gatewayRouteDb == null) {
            throw new BizException(AdminReturnCode.DATA_NOT_EXISTS);
        }
        // TODO 更新指定字段，更新人
        GatewayRoute gatewayRouteNew = new GatewayRoute();
        gatewayRouteNew.setId(gatewayRoute.getId());
        gatewayRouteNew.setAuditApplicant(String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME)));

        // TODO 更新审核,将修改内容保存到json临时字段
        if (gatewayRouteDb.getAuditState() != AuditState.PASS.getCode()) {
            throw new BizException(AdminReturnCode.DATA_PROCESSING);
        }
        GatewayRoute gatewayRouteTemp = new GatewayRoute();
        gatewayRouteTemp.setRouteId(gatewayRoute.getRouteId());
        gatewayRouteTemp.setUri(gatewayRoute.getUri());
        gatewayRouteTemp.setPredicates(gatewayRoute.getPredicates());
        gatewayRouteTemp.setFilters(gatewayRoute.getFilters());
        gatewayRouteTemp.setOrders(gatewayRoute.getOrders());
        gatewayRouteTemp.setDescription(gatewayRoute.getDescription());
        gatewayRouteTemp.setState(gatewayRoute.getState());

        gatewayRouteNew.setAuditState(AuditState.UPDATE.getCode());
        gatewayRouteNew.setAuditTemp(JSONObject.toJSONString(gatewayRouteTemp));
        return mapper.updateByUkSelective(gatewayRouteNew);
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int deleteBatch(Object[] ids) {
        int resultNum = 0;
        for (Object id : ids) {
            // TODO 删除审核
            GatewayRoute gatewayRouteDb = mapper.selectByUk(id);
            if (gatewayRouteDb.getAuditState() != AuditState.PASS.getCode()) {
                throw new BizException(AdminReturnCode.DATA_PROCESSING);
            }
            GatewayRoute gatewayRouteNew = new GatewayRoute();
            gatewayRouteNew.setId(gatewayRouteDb.getId());
            gatewayRouteNew.setAuditApplicant(String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME)));
            gatewayRouteNew.setAuditState(AuditState.DELETE.getCode());
            resultNum = resultNum + mapper.updateByUkSelective(gatewayRouteNew);
        }
        return resultNum;
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int auditingBatch(Object[] ids, boolean pass) {
        int resultNum = 0;
        String userCode = String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME));
        for (Object id : ids) {
            GatewayRoute gatewayRouteDb = mapper.selectByUk(id);
            if (gatewayRouteDb.getAuditApplicant().equals(userCode)) {
                throw new BizException(AdminReturnCode.DATA_SELF_AUDIT);
            }
            if (gatewayRouteDb.getAuditState() == AuditState.PASS.getCode()) {
                continue;
            }
            GatewayRoute gatewayRouteNew = new GatewayRoute();
            if (pass) {
                //修改审核
                if (AuditState.UPDATE.getCode() == gatewayRouteDb.getAuditState()) {
                    String object = gatewayRouteDb.getAuditTemp();
                    if (StringUtils.isBlank(object)) {
                        throw new BizException(AdminReturnCode.DATA_NOT_EXISTS);
                    }
                    GatewayRoute gatewayRoute = JSONObject.parseObject(object, GatewayRoute.class);
                    BeanUtils.copyProperties(gatewayRoute, gatewayRouteNew);
                }
                //新增审核通过生效
                if (AuditState.ADD.getCode() == gatewayRouteDb.getAuditState()) {
                    gatewayRouteNew.setState(State.ENABLE.getCode());
                }
                //删除审核
                if (AuditState.DELETE.getCode() == gatewayRouteDb.getAuditState()) {
                    resultNum = resultNum + mapper.deleteByUk(gatewayRouteDb);
                    continue;
                }
            } else {
                //新增审核不通过删除
                if (AuditState.ADD.getCode() == gatewayRouteDb.getAuditState()) {
                    resultNum = resultNum + mapper.deleteByUk(gatewayRouteDb);
                    continue;
                }
            }
            gatewayRouteNew.setId(gatewayRouteDb.getId());
            gatewayRouteNew.setAuditUser(userCode);
            gatewayRouteNew.setUpdateTime(DateUtil.date());
            //清除审核标记
            gatewayRouteNew.setAuditState(AuditState.PASS.getCode());
            gatewayRouteNew.setAuditTemp("{}");
            resultNum = resultNum + mapper.updateByUkSelective(gatewayRouteNew);
        }
        return resultNum;
    }

}
